package com.gprinter.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.adeel.library.easyFTP;
import com.github.czy1121.view.RoundButton;

import com.gprinter.http.Okhttp;
import com.gprinter.utils.FullyGridLayoutManager;
import com.gprinter.utils.GridImageAdapter;
import com.gprinter.utils.Photo_Bean;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sample.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;



public class TJ_Activity extends Activity {

    @BindView(R.id.img_back)
    RelativeLayout imgBack;
    @BindView(R.id.textView11)
    TextView textView11;
    @BindView(R.id.bbhs)
    TextView bbhs;
    @BindView(R.id.textView7)
    TextView textView7;

    @BindView(R.id.layout_help)
    RelativeLayout layoutHelp;
    @BindView(R.id.editText)
    TextView editText;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.qs)
    RoundButton qs;
    @BindView(R.id.activity_seetting)
    LinearLayout activitySeetting;
    GridImageAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private int themeId;
    LocalMedia media;
    ArrayList<Photo_Bean> photo_been = new ArrayList<Photo_Bean>();
    String TAG = "TJ_Activity";
    String duijiema  ;
    String idd  ;
    String dingdanhao ;
    String id;
    String LoginName;
    String dizhi;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_td);
        duijiema = getIntent().getStringExtra("key1");
        idd = getIntent().getStringExtra("key2");
        dingdanhao = getIntent().getStringExtra("key3");
        dizhi = getIntent().getStringExtra("key4");
//        LoginName = z_userInfoDao.query2().getLoginName();
        ButterKnife.bind(this);
        textView7.setText(dingdanhao);
        editText.setText(idd);
        initview();

    }

    private void initview() {
        themeId = R.style.picture_default_style;
        FullyGridLayoutManager manager = new FullyGridLayoutManager(TJ_Activity.this, 4, GridLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(manager);
        adapter = new GridImageAdapter(TJ_Activity.this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(5);
        recycler.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivitysss.this).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(TJ_Activity.this).externalPicturePreview(position, selectList);
                            break;


                    }
                }
            }
        });


    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {


            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(TJ_Activity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                    .maxSelectNum(3)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(3)// 每行显示个数
                    .selectionMode(
                            PictureConfig.MULTIPLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    .compressGrade(Luban.THIRD_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                    .enableCrop(false)// 是否裁剪
                    .compress(true)// 是否压缩
                    .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                    .selectionMedia(selectList)// 是否传入已选图片
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }


    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    Log.e("3344", "onActivityResult:" + selectList.size());
                    break;
            }

        } else {
            if (resultCode == 999) {
                Bundle b = data.getExtras(); //data为B中回传的Intent
                String str = b.getString("ewm");//str即为回传的值
                textView7.setText(str);
            }
        }
    }

    Photo_Bean photo;
    String jsosns;

    public void shangchuan() {
        for (int i = 0; i < selectList.size(); i++) {
            String compressPath = selectList.get(i).getCompressPath();
            Log.e(TAG, "xx:"+compressPath);
//            Log.e("7788", compressPath);
//            Bitmap bitmap = BitmapFactory.decodeFile(compressPath);
//            String cv = Utils.BitmapToString(bitmap);
//            photo = new Photo_Bean();
//            photo.setImgCode(cv);
//            long s = System.currentTimeMillis()+i*2;
//            Date date = new Date(s);
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

//            String format = sdf.format(date);
//            photo.setImgName(format + ".jpg");
//            photo_been.add(photo);
        }
//        jsosns = JSONUtils.listToJson(photo_been);
//        qingqiu();

    }

    //
//    public void qingqiu() {
//        API.TJ(textView7.getText().toString(), editText.getText().toString(), jsosns, id, LoginName, new Okhttp.Objectcallback() {
//            @Override
//            public void onsuccess(String st) {
//                Log.e(TAG, "xx" + st);
//                if (dialog != null) {
//                    dialog.dismiss();
//                }
//                if (!TextUtils.isEmpty(st)) {
//                    QS_FH_Bean qs_fh_bean = JSONUtils.parseJSON(st, QS_FH_Bean.class);
//                    if (qs_fh_bean.isSucess()) {
//                        Toast.makeText(TJ_Activity.this, "退件成功", Toast.LENGTH_SHORT).show();
//                        PictureFileUtils.deleteCacheDirFile(TJ_Activity.this);
//                        finish();
//                    } else {
//                        Toast.makeText(TJ_Activity.this, "退件失败", Toast.LENGTH_SHORT).show();
//                    }
//
//                } else {
//                    Toast.makeText(TJ_Activity.this, "系统错误", Toast.LENGTH_SHORT).show();
//                }
//            }
//
//            @Override
//            public void onFalia(int code, String errst) {
//                if (dialog != null) {
//                    dialog.dismiss();
//                }
//                Toast.makeText(TJ_Activity.this, "网络错误"+errst, Toast.LENGTH_SHORT).show();
//            }
//        });
//    }

    List<String> ccList = new ArrayList<String>();
    @OnClick({R.id.img_back, R.id.qs, R.id.cs})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.qs:

                tuijian();
                break;
            case R.id.cs:
                Intent intent = new Intent(this, ScanActivity.class);
                startActivityForResult(intent, 999);
                break;
        }
    }
    int q;
    StringBuilder stringBuilder=new StringBuilder();
    public void tuijian() {
//        textView7.setText("111");
//        editText.setText("111");
//        if (TextUtils.isEmpty(textView7.getText().toString())) {
//            Toast.makeText(this, "请输入订单号", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        if (TextUtils.isEmpty(editText.getText().toString())) {
//            Toast.makeText(this, "请输入问题描述", Toast.LENGTH_SHORT).show();
//            return;
//        }

         if (selectList.size() == 0) {
             Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
             return;
         }
        ccList.clear();
        showdialog();
        q=0;
        stringBuilder.setLength( 0 );
        for (int i = 0; i < selectList.size(); i++) {
            final int finalI = i;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    up(  selectList.get(finalI).getCompressPath());
                }
            },100);


        }



//            jsosns = "";
//            showdialog();
//            qingqiu();
//        } else {
//            showdialog();
//            shangchuan();
//        }
    }
    KProgressHUD dialog;

    public void showdialog() {
        dialog = KProgressHUD.create(TJ_Activity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在上传中，请稍候")
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();
    }










    public  void up(  String path){

        String address=dizhi;
        String     u=duijiema;
        String     p=duijiema;
        String      directory=path;
        String      mingming=dingdanhao;
         uploadTask async=new  uploadTask();
        async.execute(address,u,p,directory,mingming);//Passing arguments to AsyncThread
    }
//    ProgressDialog prg;
    class uploadTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute(){
            super.onPreExecute();

//            prg = new ProgressDialog(TJ_Activity.this);
//            prg.setMessage("Uploading...");
//            prg.show();
        }
        @Override
        protected String doInBackground(String... params) {
            Log.e(TAG, "xx0:+"+params[0]);
            Log.e(TAG, "xx1:+"+params[1]);
            Log.e(TAG, "xx2:+"+params[2]);
            Log.e(TAG, "xx3:+"+params[3]);
            String weizhui = params[3].substring(params[3].lastIndexOf(".")+1);
            Log.e(TAG, "xxxEE:"+weizhui);
            try {
                easyFTP ftp = new easyFTP();
                File file = new File(params[3]);


                //1.打开一个输入流
                InputStream is=new FileInputStream(file);
                ftp.connect(params[0],params[1],params[2]);
                boolean status=false;
                if (!params[3].isEmpty()){
                    status=ftp.setWorkingDirectory(params[3]); // if User say provided any Destination then Set it , otherwise
                }

                int suijishus = (int) (1 + Math.random() * 10);
                 String name=  params[4]+"_"+timeStamp()+suijishus+"."+weizhui;
                ftp.uploadFile(is,name );

                ccList.add(name);
                return new String("上传成功");
            }catch (Exception e){
                String t="Failure : " + e.getLocalizedMessage();
                return t;
            }
        }

        @Override
        protected void onPostExecute(String str) {
            if (str.contains("Failure")) {
                if (dialog!=null) {
                    dialog.dismiss();
                    Toast.makeText( TJ_Activity.this,str,Toast.LENGTH_LONG).show();
                return;
            }   }
            q++;
            if (dialog!=null&&selectList.size()==q) {
                dialog.dismiss();
                Log.e(TAG, "关闭了"+q);

                for (int i = 0; i < ccList.size(); i++) {
                    Log.e("rrrr", ccList.get(i));

                    stringBuilder.append( ccList.get(i));
                    stringBuilder.append("*");
                    Log.e("rrrr", "V"+ccList.size());

//                  123123123&id=第二个参数&piclist=5454_54.jpg*65465_5454.jpg
                }

                    String dd="http://www.zhikesys.top/appfinanceAddpic.aspx?duijiema="+duijiema+"&id="+dingdanhao+"&piclist="+stringBuilder;
                    Log.e(TAG, "dd:"+dd);
                Okhttp.get(dd, null, new Okhttp.Objectcallback() {
                    @Override
                    public void onsuccess(String st) {
                        Log.e(TAG, "qw1"+st);
finish();

                    }

                    @Override
                    public void onFalia(int code, String errst) {
                        Log.e(TAG, "qw2"+errst);
                    }
                });
            }
            Log.e(TAG, "wewe"+str);
            Toast.makeText( TJ_Activity.this,str,Toast.LENGTH_LONG).show();
        }
    }
    public static String timeStamp(){
               long time = System.currentTimeMillis();
                String t = String.valueOf(time/1000);
                return t;
              }
}
